<?php

class DB {

    private static $instance = null;

    private $host;
    private $port;
    private $username;
    private $password;
    private $db;
    private $charset;
    private $conn;

    private $config;


    private function __construct($config)
    {
        $db = Config::load('database', $config);
        $this->host = $db['host'];
        $this->port = $db['port'];
        $this->username = $db['username'];
        $this->password = $db['password'];
        $this->db = $db['db'];
        $this->charset = $db['charset'];

        if ($this->conn)
        {
            $this->conn->close();
        }
        $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db, $this->port);
        $this->conn->set_charset($this->charset);

        $this->config = $config;
    }

    public function __clone()
    {
        return static::getInstance();
    }

    public static function getInstance($config = 'default')
    {
        if (!(static::$instance instanceof self) || static::$instance->config != $config)
        {
            static::$instance = new self($config);
        }
        return static::$instance;
    }

    public function query($sql)
    {
        $result = $this->conn->query($sql);
        if (!$result)
        {
            return false;
        }

        $data = $result;
        if ($result instanceof mysqli_result)
        {
            $data = array();
            while($row = $result->fetch_assoc())
            {
                $data[] = $row;
            }
        }

        $result->free();

        return $data;
    }
}
